package com.vue3.blog.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vue3.blog.common.resp.BizException;
import com.vue3.blog.common.util.MD5Util;
import com.vue3.blog.common.util.StrUtil2;
import com.vue3.blog.domain.dto.LoginDTO;
import com.vue3.blog.domain.entity.SysUser;
import com.vue3.blog.domain.vo.LoginInfoVO;
import com.vue3.blog.mapper.SysUserMapper;
import com.vue3.blog.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Mr.小朱同学
 * @version 1.0.0
 * @date 2025/6/30 12:22
 * @description 系统用户服务实现类
 */
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    /**
     * 用户登录
     */
    @Override
    public String login(LoginDTO dto) {
        // 根据用户名查询账号
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(SysUser::getUsername, StrUtil2.trim(dto.getUsername()));
        SysUser sysUser = this.getOne(wrapper);
        if (null == sysUser) {
            throw new BizException("账号不存在");
        }
        if (!Objects.equals(MD5Util.md5(dto.getPassword()), sysUser.getPassword())) {
            throw new BizException("账号或密码不正确");
        }
        // 执行登录
        StpUtil.login(sysUser.getId());
        // 返回token
        return StpUtil.getTokenValue();
    }

    /**
     * 获取用户信息
     */
    @Override
    public LoginInfoVO getUserInfo() {
        LoginInfoVO vo = new LoginInfoVO();
        // 获取token
        String token = StpUtil.getTokenValue();
        System.out.println(token);
        // 根据token获取用户信息
        SysUser sysUser = this.getById(StpUtil.getLoginIdAsLong());
        if (null == sysUser) {
            throw new BizException("账号不存在");
        }
        BeanUtils.copyProperties(sysUser, vo);
        return vo;
    }

    /**
     * 获取系统用户名称Map
     */
    @Override
    public Map<Long, String> getSysUserNameMap(Collection<Long> userIdList) {
        LambdaQueryWrapper<SysUser> wrapper = Wrappers.lambdaQuery();
        wrapper.in(CollUtil.isNotEmpty(userIdList), SysUser::getId, userIdList);
        List<SysUser> userList = this.list(wrapper);
        if (CollUtil.isEmpty(userList)) {
            return Collections.emptyMap();
        }
        return userList.stream().collect(Collectors.toMap(SysUser::getId, SysUser::getUsername));
    }
}